package me.zhengjie.modules.system.excel.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import me.zhengjie.modules.system.domain.Product;
import me.zhengjie.modules.system.domain.PurchaseData;
import me.zhengjie.modules.system.domain.WarningMessage;
import me.zhengjie.modules.system.excel.vo.ProductVo;
import me.zhengjie.modules.system.excel.vo.WarningMessageVo;
import me.zhengjie.modules.system.repository.ProductRepository;
import me.zhengjie.modules.system.repository.PurchaseDataRepository;
import me.zhengjie.modules.system.repository.WarningMessageRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class WarningMessageListener extends AnalysisEventListener<WarningMessageVo> {

    @Autowired
    private WarningMessageRepository warningMessageRepository;

    @Autowired
    private PurchaseDataRepository purchaseDataRepository;

    private List<WarningMessage> warningMessageList = new ArrayList<>();

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        warningMessageList = new ArrayList<>();
        warningMessageRepository.deleteAll();
    }

    @Override
    public void invoke(WarningMessageVo warningMessageVo, AnalysisContext analysisContext) {
        WarningMessage w = new WarningMessage();
        BeanUtils.copyProperties(warningMessageVo, w);

        List<PurchaseData> purchaseDataList = purchaseDataRepository.findByCustomerAndModel("备", warningMessageVo.getModel());
        Integer onPassageQuantitySum = purchaseDataList.stream().collect(Collectors.summingInt(PurchaseData::getOnPassageQuantity));
        w.setOnPassageQuantity(onPassageQuantitySum);
        w.setPurchaseTime(purchaseDataList.size());
        w.setQuantity(purchaseDataList.stream().mapToInt(obj -> obj.getQuantity()).sum());
        Integer overMinStoke = new BigDecimal(warningMessageVo.getStock()).add(new BigDecimal(onPassageQuantitySum)).
                subtract(new BigDecimal(warningMessageVo.getMiniStock())).intValue();
        w.setOverMinStoke(overMinStoke);
        if (overMinStoke < 0) {
            warningMessageList.add(w);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        warningMessageRepository.saveAll(warningMessageList);
    }
}
